<?php

namespace App\Http\Controllers\platform;

use App\Http\Controllers\Controller;
use App\Jobs\StudyReaordTime;
use App\Models\StudyUserRecord;
use Illuminate\Http\Request;

class StudyReaordController extends Controller
{
    public function index(Request $Request)
    {
        if(!$Request->uid){
            return response()->json(['code' => '403', 'msg' => '请选择用户']);
        }
        if(!$Request->course_id){
            return response()->json(['code' => '403', 'msg' => '请选择课程']);
        }
        if(!$Request->video_id){
            return response()->json(['code' => '403', 'msg' => '请选择视频']);
        }
        
        if ($Request->study_length <= 0){
            return response()->json(['code' => '403', 'msg' => '学习时间错误']);
        }
        
        $time = time();
        $data = [
            'course_id'=>$Request->course_id,
            'video_id'=>$Request->video_id,
            'study_length'=>$Request->study_length,
            'uid'=>$Request->uid,
            'eid'=>$Request->eid,
            'task_id'=>$Request->task_id ?? 0,
            'time'=>$time,
        ];
        $data['study_length'] = ceil($data['study_length']);
        //写入队列
        StudyReaordTime::dispatch($data)->onQueue('openapi_study_record_time');
        return response()->json(['code' => '200', 'data' => $data]);
    }

    public function record(Request $Request)
    {
        if(!$Request->uid){
            return response()->json(['code' => '403', 'msg' => '请选择用户']);
        }
        $search = $Request->search_key;
        $limit = $Request->limit ?: 15;
        $num = $Request->num ?: 15;
        $page = $Request->page ?: 1;
        $skip = $page * $limit - $limit;
        $sql = StudyUserRecord::with('course')->with('video')->where('uid',$Request->uid);
        $total = $sql->count();
        $data = $sql->skip($skip)->take($limit)->orderBy('update_time','desc')->get();
        foreach ($data as $key => $value) {
            $data[$key]->cover_img = '';
            $data[$key]->cover_name = '';
            $data[$key]->cover_uniqid = '';

            $data[$key]->video_name = '';
            $data[$key]->video_duration = '';
            
            if($value->course){
                $data[$key]->cover_img = $value->course->cover_img;
                $data[$key]->cover_name = $value->course->name;
                $data[$key]->cover_uniqid = $value->course->uniqid;
            }

            if($value->video){
                $data[$key]->video_name = $value->video->title;
                $data[$key]->video_duration = $value->video->duration;
            }

            $data[$key]->cumulation_time = $value->study_length;
        }
        $res = [];
        $res['count'] = $total;
        $res['page'] = $page;
        $res['limit'] = $limit;
        $res['num'] = $num;
        $res['list'] = $data;
        return response()->json(['code' => '200', 'data' => $res]);
    }
}
